package org.test.jpa.model;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

import javax.persistence.*;

import org.test.jpa.model.transfer.EmployeeTO;

/**
 * Employee class
 * 
 * @author vitalii
 *
 */

@Entity
@Table(name = "employee")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="ETYPE", discriminatorType=DiscriminatorType.STRING,length=10)
@DiscriminatorValue("EMPL")
@NamedQueries({
    @NamedQuery(name="employeeForProject",
        query="SELECT e FROM Employee e JOIN e.projects p WHERE p=:project"),
    @NamedQuery(name="employeeInDepartment",
        query="SELECT e FROM Employee e WHERE e.department=:department"),
    @NamedQuery(name="employeeByFullName",
        query="SELECT e FROM Employee e WHERE e.firstName=:firstName")        
})
public class Employee 
{
	@TableGenerator(
		     name="employee_Gen",
			 table="ID_GEN",
			 pkColumnName="GEN_NAME",
			 valueColumnName="GEN_VAL")

	@Id
	@GeneratedValue(strategy=GenerationType.TABLE, generator="employee_Gen")
	private long id;

	@Basic private String firstName;
	@Basic private String lastName;

	// One employee can be owned by one department and 
	// one department can own many employee.
	// RELATIONSHIP: Many ( Employee ) To One ( Department )
	// This relationship managed by EJB code
	@ManyToOne(optional=false,fetch=FetchType.LAZY)
	@JoinColumn(name="DEPARTMENT_ID", nullable=false)
	Department department;

	// This relationship encapsulated by entity ( using JPA )
	@OneToMany(cascade=CascadeType.ALL)
	@JoinTable(name="EMP_PHONES")
    private Set<Phone> phones = new HashSet<Phone>();

	// One employee can be assigned to many projects and
	// one project can contain many employee
	// RELATIONSHIP: Many ( Employee ) To Many ( Projects )
	// This relationship managed by EJB code
	@ManyToMany
    @JoinTable(name="EMP_PROJ",
                joinColumns=@JoinColumn(name="EMP_ID"),
                inverseJoinColumns=@JoinColumn(name="PROJ_ID")
    )
    private Collection<Project> projects = new LinkedList<Project>();	

	public long getID()
	{
		return id;
	}
	
	public Department getDepartment()
	{
		return department;
	}

	public String getFirstName()
	{
		return firstName;
	}	
	
	public Set<Phone> getPhones()
	{
		return phones;
	}
	
	public void addPhone(Phone phone)
	{
		phones.add(phone);
	}
	
	public void addProject(Project project)
	{
		projects.add(project);
	}
	
	public void setDepartment(Department department)
	{
		this.department = department;
	}

	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public void copyTo(EmployeeTO employeeTO)
	{
		employeeTO.firstName = firstName;
		employeeTO.lastName = lastName;		
		
		employeeTO.departmentID = department.getID();
	}
}
